package com.m.system.controller;

import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.alibaba.fastjson.JSON;
import com.client.job.utils.DataResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.m.system.domain.SysRoleEntity;
import com.m.system.domain.SysUserEntity;
import com.m.system.domain.UserRoleDomain;
import com.m.system.service.SysRoleService;
import com.m.system.service.SysUserRoleService;
import com.m.system.service.SysUserService;
import com.m.utils.PageSearchDomain;
import com.m.utils.UserUtil;
import com.m.utils.ValidResult;
import com.m.utils.ValidationUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * 用户信息表Controller
 * 
 * @author monxz
 * @version 2021-01-29
 */
@RestController
@RequestMapping(value = "user/sysUser")
@Api(tags = "用户信息表")
public class SysUserController  {

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysRoleService sysRoleService;

	@Autowired
	private SysUserRoleService sysUserRoleService;

	@PostMapping(value = "/list")
	@ApiOperation("用户分页查询")
	public DataResult list(@RequestBody  PageSearchDomain<SysUserEntity>  pageSearchDomain) throws Exception {
		PageHelper.startPage(pageSearchDomain.getPageNum(),pageSearchDomain.getPageSize());
		PageInfo<SysUserEntity> page = new PageInfo<>(sysUserService.findSysUserList(pageSearchDomain.getObj()));
		return DataResult.buildSuccess(page);
	}

	@PostMapping(value = "/save")
	@ApiOperation("新增用户")
	public DataResult save(@RequestBody SysUserEntity sysUserPojo) throws Exception {
		// 校验接口参数
		ValidResult validResult = ValidationUtils.validateGroup(sysUserPojo);
		if (validResult.isHasErrors()) {
			return DataResult.buildFail(validResult.getErrorMsg());
		}

		SysUserEntity  checkUser = new SysUserEntity();
		checkUser.setUserName(sysUserPojo.getUserName());
		if(sysUserService.checkUnion(checkUser) == 1) {
			return DataResult.buildFail("用户名已经存在");
		}
		
		return DataResult.buildByInter(sysUserService.addSysUser(sysUserPojo));
	}

	@PostMapping(value = "/update")
	@ApiOperation("修改用户")
	public DataResult update(@RequestBody SysUserEntity sysUserPojo) throws Exception {
		// 主键判断
		if (sysUserPojo.getUserId() == null) {
			return DataResult.buildFail("没有对应的Id");
		}
		return DataResult.buildByInter(sysUserService.modifySysUser(sysUserPojo));

	}

	@PostMapping(value = "/delete")
	@ApiOperation("删除用户")
	public DataResult delete(@RequestBody String ids) throws Exception {
		if (ids == null || ids.trim().length() == 0) {
			return DataResult.buildFail("参数不能为空");
		}
		List<String> objs = JSON.parseArray(ids, String.class);
		return DataResult.buildByInter(sysUserService.deleteFalse(objs.toArray(new String[0])));
	}

	

	@GetMapping(value = "/getUser/{userId}")
	@ApiOperation("获取用户详情")
	public DataResult getUser(@PathVariable("userId") String userId) throws Exception {
		if (userId == null || userId.isEmpty() || userId.equals("null")) {
			return DataResult.buildSuccess(sysRoleService.findSysRoleList(new SysRoleEntity()));
		}
		SysUserEntity user = new SysUserEntity();
		user.setUserId(userId);
		user = sysUserService.findSysUserById(user);
		user.setRoleList(sysRoleService.findSysRoleList(new SysRoleEntity()));
		UserRoleDomain ur = new UserRoleDomain(userId, null);
		user.setRoleIds(sysUserRoleService.listUserRole(ur).stream().map(UserRoleDomain::getRoleId)
				.collect(Collectors.toList()));
		return DataResult.buildSuccess(user);
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/restPwd")
	@ApiOperation("重置密码")
	public DataResult restPwd(@RequestBody String josn) throws Exception {
		Map<String, String> param = JSON.parseObject(josn, Map.class);
		return DataResult.buildSuccess(sysUserService.restPwd(param.get("userId"), param.get("password"), null));
	}

	@GetMapping("/currentUser")
	@ApiOperation("获取到当前用户信息")
	public DataResult getUser() {
		return DataResult.buildSuccess(UserUtil.getUser(null));
	}

	@SuppressWarnings({ "unchecked" })
	@PostMapping("/updPwd")
	@ApiOperation("修改当前用户密码")
	public DataResult updPwd(@RequestBody String josn) throws Exception {
		Map<String, String> map = JSON.parseObject(josn, Map.class);
		Integer res = sysUserService.restPwd(UserUtil.getUserId(null), map.get("newPassword"), map.get("oldPassword"));
		if (res == 0) {
			return DataResult.buildFail("旧密码不正确");
		}
		return DataResult.buildSuccess();
	}

}